package services

import (
	"context"
	"github.com/golang/protobuf/ptypes/empty"
	"github.com/golang/protobuf/ptypes/wrappers"
	"sort"

	context2 "kop/framework/context"
	"kop/framework/errors"
	"kop/modules/battle/models/battle"
	"kop/pb"

	captainC "kop/modules/captain/client"
	moneyC "kop/modules/money/client"
	questC "kop/modules/quest/client"
	stageC "kop/modules/stage/client"
)

type StageService struct {
	context2.Context
}

// 获取当前主线关卡
func (s *StageService) GetStage(ctx context.Context, _ *empty.Empty) (*pb.Stage, error) {

	return stageC.GetStage(ctx), nil
}

func (s *StageService) Walk(ctx context.Context, req *empty.Empty) (*pb.WalkReply, error) {

	return stageC.StageService.Walk(ctx, req)
}

// 事件类型2
func (s *StageService) Event2(ctx context.Context, req *wrappers.Int32Value) (*pb.StageEventResp, error) {

	return stageC.StageService.Event2(ctx, req)
}

// 事件类型3
func (s *StageService) Event3(ctx context.Context, req *wrappers.Int32Value) (*pb.StageEventResp, error) {

	return stageC.StageService.Event3(ctx, req)
}

// 主线关卡战斗
func (s *StageService) Battle(ctx context.Context, _ *empty.Empty) (*pb.BattleReply, error) {

	var reply pb.BattleReply

	var roleID = s.GetRoleID(ctx)

	var stage = stageC.GetStage(ctx)
	reply.Stage = stage

	if stage.Boss == nil {
		return &reply, errors.New("还没到BOSS")
	}

	var err error
	if _, err = moneyC.SubCoin(ctx, stage.WalkCoin); err != nil {
		return &reply, err
	}

	reply.Fighter1 = captainC.GetCaptainsByReady(roleID)

	// 技能数据不需要
	defer Captains(reply.Fighter1).setSkillNil()

	reply.Fighter2 = []*pb.Captain{reply.Stage.Boss}

	sort.Sort(Captains(reply.Fighter1))

	reply.BattleResult, err = battle.Battle(reply.Fighter1, reply.Fighter2)
	if err != nil {
		return &reply, err
	}

	if reply.BattleResult.Win {

		var stageID = reply.Stage.StageID
		reply.Award = stageC.Next(reply.Stage)

		// quest , daily quest
		questC.Stage(roleID, stageID)
		questC.DailyQuestStage(roleID)
	}

	return &reply, nil
}
